﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using TfsComLib.TfsBranchLib2;

namespace TfsBranchLib2.View
{
    /// <summary>
    ///     Interaction logic for RecentBranchSetPopup.xaml
    /// </summary>
    public partial class RecentBranchSetPopup : Window
    {
        private BranchSet branchSet;
        private readonly IBranchedHistory context;

        //private List<BranchData> branches;

        public RecentBranchSetPopup()
        {
            InitializeComponent();
        }

        public RecentBranchSetPopup(IBranchedHistory context) : this()
        {
            this.context = context;
            branchSetsList.SetBinding(ItemsControl.ItemsSourceProperty,
                new Binding("Items") {Source = context.RecentBranchSets, Mode = BindingMode.OneWay});
        }

        private void branchSetsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = branchSetsList.SelectedValue as BranchSetItem;
            if (selectedItem == null) return;
            if (selectedItem.ItemType == BranchSetItemType.Standard)
            {
                branchSet = selectedItem.BranchSetValue.PrecedentValue;
                branchList.ItemsSource = branchSet;
            }
            else
            {
                branchSet = null;
                branchList.ItemsSource = null;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            // Just close
            // Do not apply selection
        }

        private void SetSelectedBranches(object sender, RoutedEventArgs e)
        {
            if (branchSet != null)
            {
                var list = branchSet.ToList();
                context.SelectedBranchesCache.SetRecentBranches(list);
            }
            Close();
        }

        private void CancelAndClose(object sender, RoutedEventArgs e)
        {
            // Just close
            Close();
        }
    }
}